package com.itchen.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itchen.domain.dto.PermissionDTO;
import com.itchen.domain.entity.Permission;
import com.itchen.domain.entity.Role;
import com.itchen.domain.entity.User;
import com.itchen.mapper.PermissionMapper;
import com.itchen.service.PermissionService;
import com.itchen.service.RoleService;
import com.itchen.utils.JwtTokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import java.util.Comparator;

/**
 * 权限服务实现类
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    private final RoleService roleService;

    public PermissionServiceImpl(RoleService roleService) {
        this.roleService = roleService;
    }

    @Override
    public List<PermissionDTO> getPermissionTree() {
        // 获取所有权限
        List<Permission> permissions = this.list(new LambdaQueryWrapper<Permission>()
                .orderByAsc(Permission::getPid)
                .orderByAsc(Permission::getOrders));
        
        // 转换为DTO
        List<PermissionDTO> dtoList = permissions.stream().map(this::convertToDto).collect(Collectors.toList());
        
        // 构建树形结构
        List<PermissionDTO> tree = buildTree(dtoList);
        
        return tree;
    }
    
    @Override
    public List<PermissionDTO> getUserMenu() {
        // 获取此用户的角色
        User currentUser = JwtTokenUtils.getCurrentUser();
        String role = currentUser.getRole();
        // 根据角色获取权限
        Role roleBean = roleService.getByRoleName(role);
        String[] permissionList = roleBean.getPid().split(",");

        List<Permission> permissions = new ArrayList<>();
        for (String pid : permissionList) {
            Permission permission = this.getById(Integer.parseInt(pid));
            if (permission != null) {
                if (permission.getIsShow() == 1) {
                    permissions.add(permission);
                }
            }
        }

        // 对权限列表按照orders字段排序
        permissions.sort(Comparator.comparing(Permission::getOrders));

        // 转换为DTO
        List<PermissionDTO> dtoList = permissions.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
        
        // 构建树形结构
        return buildTree(dtoList);
    }

    @Override
    public List<Permission> listAllPermissions() {
        return this.list(new LambdaQueryWrapper<Permission>()
                .orderByAsc(Permission::getPid)
                .orderByAsc(Permission::getOrders));
    }

    @Override
    public Permission getPermissionById(Integer id) {
        return this.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addPermission(Permission permission) {
        if (permission.getCreateTime() == null) {
            permission.setCreateTime(new Date());
        }
        permission.setUpdateTime(new Date());
        return this.save(permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePermission(Permission permission) {
        permission.setUpdateTime(new Date());
        return this.updateById(permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePermission(Integer id) {
        // 先查询是否有子权限
        List<Permission> children = this.list(new LambdaQueryWrapper<Permission>()
                .eq(Permission::getPid, id));
        
        if (!children.isEmpty()) {
            // 有子权限，先删除子权限
            List<Integer> childIds = children.stream().map(Permission::getId).collect(Collectors.toList());
            this.removeByIds(childIds);
        }
        
        // 删除当前权限
        return this.removeById(id);
    }
    
    /**
     * 转换实体到DTO
     */
    private PermissionDTO convertToDto(Permission permission) {
        PermissionDTO dto = new PermissionDTO();
        BeanUtils.copyProperties(permission, dto);
        return dto;
    }
    
    /**
     * 构建树形结构
     */
    private List<PermissionDTO> buildTree(List<PermissionDTO> dtoList) {
        List<PermissionDTO> tree = new ArrayList<>();
        Map<Integer, PermissionDTO> map = new HashMap<>();
        
        // 将所有节点放入map
        for (PermissionDTO dto : dtoList) {
            map.put(dto.getId(), dto);
        }
        
        // 构建树
        for (PermissionDTO dto : dtoList) {
            // 父节点
            PermissionDTO parent = map.get(dto.getPid());
            if (parent != null) {
                // 将当前节点添加到父节点的children
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(dto);
            } else {
                // 如果没有父节点，则为顶级节点
                tree.add(dto);
            }
        }
        
        // 对树的每一层级进行排序
        sortTreeByOrders(tree);
        
        return tree;
    }
    
    /**
     * 递归对树的每一层级按照orders字段进行排序
     */
    private void sortTreeByOrders(List<PermissionDTO> tree) {
        if (tree == null || tree.isEmpty()) {
            return;
        }
        
        // 对当前层级排序
        tree.sort(Comparator.comparing(PermissionDTO::getOrders));
        
        // 递归排序子节点
        for (PermissionDTO node : tree) {
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                sortTreeByOrders(node.getChildren());
            }
        }
    }
} 